package com.whu.helpluojia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whu.helpluojia.dao.CommentDao;
import com.whu.helpluojia.dao.ConsultDao;
import com.whu.helpluojia.dao.FindDao;
import com.whu.helpluojia.dao.RecordDao;
import com.whu.helpluojia.domain.*;
import com.whu.helpluojia.domain.dto.CommentDto;
import com.whu.helpluojia.service.CommentService;
import com.whu.helpluojia.service.ConsultService;
import com.whu.helpluojia.service.FindService;
import com.whu.helpluojia.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentDao, Comment> implements CommentService {

    @Autowired
    CommentDao commentDao;

    @Autowired
    UserService userService;

    @Autowired
    RecordDao recordDao;

    @Autowired
    ConsultDao consultDao;

    @Override
    public void addComment(Long userId, Comment comment) {
        comment.setUserId(userId);
        comment.setTime(new Date());
        commentDao.insert(comment);

        Consult consult=consultDao.selectById(comment.getConsultId());
        Record record=new Record();
        record.setType(consult.getType());
        record.setUserId(comment.getUserId());
        recordDao.insert(record);
    }

    @Override
    public List<CommentDto> getCommentByConsultId(Long id) {

        LambdaQueryWrapper<Comment> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getConsultId,id);
        queryWrapper.orderByAsc(Comment::getTime);
        List<Comment>comments=commentDao.selectList(queryWrapper);

        if(comments!=null){
            List<CommentDto>commentDtos=addInformation(comments);
            return commentDtos;
        }

        return null;
    }

    public List<CommentDto> addInformation(List<Comment> comments){

        List<CommentDto>commentDtos=new ArrayList<>();
        User[] users=userService.selectAll();
        Map<Long,User> userMap=new HashMap<>();

        for(User user:users){
            userMap.put(user.getId(),user);
        }
        for(Comment comment:comments){
            CommentDto commentDto=new CommentDto();
            BeanUtils.copyProperties(comment,commentDto);
            commentDto.setSex(userMap.get(comment.getUserId()).getGender());
            commentDto.setUserName(userMap.get(comment.getUserId()).getName());
            commentDtos.add(commentDto);
        }

        return commentDtos;
    }
}
